define(['jquery' ,'api', 'echarts', 'webSocketModule', 'httpModule', 'mustache', 'moment'], function($, api, echarts, webSocketModule, httpModule, mustache, moment) {
  var that = {};
  var $node;
  var chartMap = {};
  var chartSeries = [];
  var date = [];
  var cacheTpl = {};
  var chartGroupList = [];
  var chartFilterList = [];
  var screenId;
  var chartList;
  var dateMap = {};
  var chartSeriesMap = {};

  var lineList = ['line1', 'line2', 'line3', 'line4', 'line5'];
  var cacheChart = {};

  var initSocket = function(ids) {
    webSocketModule.initSocket(ids);
    webSocketModule.onMessage(that.updateChart);
  };

  var closeSocket = function() {
    webSocketModule.closeSocket();
  };

  var updateChart = function(msg) {
    msg.result && msg.result.map(function(item) {
      var items = item.gitems;
      var lineItem = item.items;
      var flag = false;
      var lineList = [];

      // 临时保存本次msg的时间列表

      var dateList = [];
      var chartSeriesList = [];

      lineItem && lineItem.map(function(line) {
        lineList.push(line.name_);
      });

      items && items.map(function(data) {
        if (data.items && data.items.length > 0) {

          if (!flag) {
            flag = true;
            data.items && data.items.map(function(item) {
              dateList.push(moment(parseInt(item.clock * 1000)).format('YYYY-MM-DD HH:mm:ss'));
            });
          };
        };
      });

      dateMap[item.graphid] = dateMap[item.graphid] || [];
      dateMap[item.graphid] = dateMap[item.graphid].concat(dateList);
      chartSeriesMap[item.graphid] = chartSeriesMap[item.graphid] || [];

      items && items.map(function(data) {
        chartSeriesMap[item.graphid] && chartSeriesMap[item.graphid].map(function(serie) {

          if (dateMap[item.graphid].length) {

            if (data.gitemid === serie.gitemId && data.items && data.items.length) {
              var items = [];
              data.items && data.items.map(function(item) {
                items.push(item.value);
              });
              serie.data = serie.data.concat(items);
            } else {

              if (dateMap[item.graphid].length) {

                if (serie.data[serie.data.length - 1]) {
                  serie.data.push(serie.data[serie.data.length - 1]);
                };
                // serie.data.push(serie.data[serie.data.length - 1] || 0);
              };
            };
          };
        });
      });
      that.initChart(item.name, lineList, null, dateMap[item.graphid], chartSeriesMap[item.graphid]);
    });
  };

  var switchType = function() {
    $node.find('.js-chart-group-filter').find('.label').removeClass('label-info').addClass('label-default');
    $(this).removeClass('label-default').addClass('label-info');
    var count = $(this).attr('data-id');
    var endDate;
    var startDate;
    var isAll = false;
    var ids = [];

    chartList && chartList.map(function(item) {
      ids.push(item.resourceid);
    });


    if (count === '-1') {
      isAll = true;
    } else {
      endDate = Date.parse(new Date());
      startDate = endDate - (60 * count);
    };

    that.getChartSeries(ids.join(','), startDate, endDate, isAll);
  };

  var screenChange = function(evt) {
    screenId = $(this).attr('data-screen-id');
    var text = $(this).find('a').html();
    $(this).parent().prev().find('.groupText').text(text);
    chartList = chartMap[screenId];
    that.initChartFilter();
    var ids = [];
    chartList && chartList.map(function(item) {
      ids.push(item.resourceid);
    });
    that.initSocket(ids);
    cacheChart = {};
    $('.chart-date-filter').remove();
    $('.col-xs-6').remove();
    that.getChartSeries(ids.join(','));
  };

  var getScreenList = function() {
    httpModule.baseServ({
      url: api.getScreenList
    })
    .then(function(ret) {
      chartMap = {};

      // 保存聚合图形内存
      ret.result && ret.result.map(function(item) {
        chartMap[item.screenid] = item.screenitems;
      });

      that.initTpl($node.find('.js-chart-screen'), cacheTpl['dropdownMenu'], {
        title: '聚合图形',
        type: 'screenList',
        list: ret.result
      });
    });
  };

  // 获取chart数据
  var getChartSeries = function(item, startDate, endDate, isAll) {

    // 如果没传时间 默认设置为5分钟
    // if (!startDate && !endDate) {
    //   var endDate = Date.parse(new Date());
    //   var startDate = endDate - (60 * 5);
    // };
    //
    // var param = {
    //   graphids: item || ''
    // };
    //
    // if (!isAll) {
    //   param.time_from = parseInt(startDate / 1000);
    //   param.time_till = parseInt(endDate / 1000);
    // };

    // 如果没传时间 默认设置为5分钟
    if (!startDate && !endDate) {
      var endDate = Date.parse(new Date());
      var startDate = endDate - (60 * 5) * 1000;
    };

    var param = {
      graphids: item || ''
    };

    if (!isAll) {
      param.time_from = parseInt(startDate / 1000);
      param.time_till = parseInt(endDate / 1000);
    };

    for (var key in cacheChart) {
      cacheChart[key].showLoading();
    };

    // 获取数据
    httpModule.baseServ({
      url: api.getChartSeries,
      param: param
    })
    .then(function(ret) {
      var items = [];
      var dateList = [];
      var lineList = [];
      var units;
      // chartSeriesMap = [];

      ret.result && ret.result.map(function(item, index) {
        var series = [];

        if (!!item) {
          items = item.gitems;
          items && items.map(function(data) {
            dateList = [];

            var model = {
              name: data.name,
              type: "line",
              smooth: true,
              gitemId: data.gitemid,
              symbol: "none",
              sampling: "average",
              data: []
            };

            lineList.push(data.name);
            data.items && data.items.map(function(item) {
              model.data.push(item.value);
              dateList.push(moment(parseInt(item.clock * 1000)).format('YYYY-MM-DD HH:mm:ss'));
            });
            series.push(model);
          });
          units = items[0].units;
          chartSeriesMap[item.graphid] = series;
        };

        // 保存时间
        dateMap[item.graphid] = dateList;

        if ($node.find('.col-xs-6').eq(index)[0]) {
          $node.find('.col-xs-6').eq(index).find('.chart-title').html(item.name);
          $node.find('.col-xs-6').eq(index).find('.chart-subtext').html(['单位', units].join('/'));
          that.resetChart(item.name, lineList, $node.find('.col-xs-6').eq(index), dateList, chartSeriesMap[item.graphid]);
        } else {
          that.initTpl($node.find('#chartGroup'), cacheTpl['miniChartInfo'], {}, function(dom) {
            console.log('dom', dom);
            dom.find('.chart-title').html([item.hosts[0].name, item.name].join(' - '));
            dom.find('.chart-subtext').html(['单位', units].join('/'));
            that.initChart(item.name, lineList, dom, dateList, chartSeriesMap[item.graphid]);
          });
        };
      });
    });
  };

  var loadTpls = function() {
    $.get('../template/miniChartInfo.html')
    .then(function(ret) {
      cacheTpl['miniChartInfo'] = ret;
    });

    $.get('../template/dropdownMenu.html')
    .then(function(ret) {
      cacheTpl['dropdownMenu'] = ret;
    });

    $.get('../template/chartFilter.html')
    .then(function(ret) {
      cacheTpl['chartFilter'] = ret;
    });
  };

  var initTpl = function(node, tpl, data, callback, isPrev) {
    var $tpl = mustache.render(tpl, data);
    var $dom = $($tpl);

    if (isPrev) {
      node.prepend($dom);
    } else {
      node.append($dom);
    };
    callback && callback($dom);
  };

  // 初始化时间段
  var initChartFilter = function() {
    $.getJSON('../json/chartFilterList.json')
    .then(function(ret) {
      chartFilterList = ret;
      that.initTpl($node.find('.js-chart-group-filter'), cacheTpl['chartFilter'], {
        list: chartFilterList
      }, function(ret) {
        $(ret).find('.label').eq(0).removeClass('label-default').addClass('label-info');
      }, true);
    });
  };

  // 初始化图表
  var resetChart = function(title, lineList, dom, dateList, serieList) {

    setTimeout(function() {
      // 基于准备好的dom，初始化echarts图表
      var myChart = cacheChart[title] || echarts.init(dom.find('.mini-chart')[0]);

      var option = {
          color: [
              '#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#d87a80',
              '#8d98b3','#e5cf0d','#97b552','#95706d','#dc69aa',
              '#07a2a4','#9a7fd1','#588dd5','#f5994e','#c05050',
              '#59678c','#c9ab00','#7eb00a','#6f5553','#c14089'
          ],

          legend: {
            data: lineList
          },

          tooltip: {
              trigger: 'axis',
              position: function (pt) {
                  return [pt[0], '10%'];
              }
          },
          xAxis: {
              type: 'category',
              boundaryGap: false,
              data: dateList || date
          },
          yAxis: {
              type: 'value',
              boundaryGap: [0, '100%'],
              axisLabel: {
                formatter: function (value, index) {
                  var text;

                  if (value >= 1000 * 1000 * 1000 * 1000) {
                    text = (value / 1000 / 1000 / 1000 / 1000) + 'T';
                  }

                  else if (value >= 1000 * 1000 * 1000) {
                    text = (value / 1000 / 1000/ 1000) + 'G';
                  }

                  else if (value >= 1000 * 1000) {
                    text = (value / 1000 / 1000) + 'M';
                  }

                  else if (value >= 1000) {
                    text = (value / 1000) + 'K';
                  }

                  else {
                    text = value;
                  };
                  return text;
                }
              }
          },
          grid: {
            x: 60,
            x2: 60
          },
          series: serieList || chartSeries
      };

      // 为echarts对象加载数据
      if (!!!cacheChart[title]) {
        cacheChart[title] = myChart;
      } else {
        cacheChart[title].hideLoading();
      };

      cacheChart[title].setOption(option, true);
      cacheChart[title].hideLoading();
    }, 200);
  };

  // 初始化图表
  var initChart = function(title, lineList, dom, dateList, serieList) {

    // 基于准备好的dom，初始化echarts图表
    var myChart = cacheChart[title] || echarts.init(dom.find('.mini-chart')[0]);

    var option = {
        color: [
            '#2ec7c9','#b6a2de','#5ab1ef','#ffb980','#d87a80',
            '#8d98b3','#e5cf0d','#97b552','#95706d','#dc69aa',
            '#07a2a4','#9a7fd1','#588dd5','#f5994e','#c05050',
            '#59678c','#c9ab00','#7eb00a','#6f5553','#c14089'
        ],

        legend: {
          data: lineList
        },

        tooltip: {
            trigger: 'axis',
            position: function (pt) {
                return [pt[0], '10%'];
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: dateList || date
        },
        yAxis: {
            type: 'value',
            boundaryGap: [0, '100%']
        },
        grid: {
          x: 40,
          x2: 40
        },
        series: serieList || chartSeries
    };

    // 为echarts对象加载数据
    if (!!!cacheChart[title]) {
      cacheChart[title] = myChart;
    } else {
      cacheChart[title].hideLoading();
    };
    cacheChart[title].setOption(option, true);
  };

  // 初始化获取dom
  var parseDOM = function(node) {
    $node = node;
  };

  // 绑定向外暴露的方法
  var bindListener = function() {
    that.getChartSeries = getChartSeries;
    that.initChart = initChart;
    that.initChartFilter = initChartFilter;
    that.loadTpls = loadTpls;
    that.initTpl = initTpl;
    that.getScreenList = getScreenList;
    that.screenChange = screenChange;
    that.switchType = switchType;
    that.initSocket = initSocket;
    that.closeSocket = closeSocket;
    that.updateChart = updateChart;
    that.resetChart = resetChart;
  };

  // 初始化时执行的函数
  var initPlugins = function() {
    that.loadTpls();
    that.getScreenList();
    // that.getChartList();
    // that.initChartFilter();

    $node.delegate('.js-chart-screen li', 'click', screenChange);
    $node.delegate('.label-default', 'click', switchType);
  };

  var init = function(node) {
    parseDOM(node);
    bindListener();
    initPlugins();
  };

  that.parseDOM = parseDOM;
  that.bindListener = bindListener;
  that.initPlugins = initPlugins;
  that.init = init;
  return that;
});
